/**
 * 通讯前置工具库
 * 服务端限制请求接口，需要做签名或者加密
 * 这里处理随机从服务端获取签名私钥，加密公钥。非对称国密2
 * 加密公钥和签名私钥有效时长为半小时
 * 客户端需要判断有效时长，配合后端返回错误信息或者二次获取
 * 示例
 * {
 *     "code": "1",
 *     "fail": false,
 *     "data": {
 *         "privateKey": "00fba49dfbd845c483186bf43f7bd24d7d658f04caf9ffe77b6113f4678725bedf",
 *         "publicKey": "0414a3ede204cc9a4c142ba121e9c2ab6520c8728451972dab4da376ae2f35c60904500927662963ad806883012bb390fb2ae03ff2cddb1cac387a47c0a4ba5d75",
 *         "IPKT-Authorization": "7882a5ac2082451f935e5357aec70b73"
 *     }
 * }
 * 请求头需要携带签名标识 IPKT-Authorization
 */
import axios from 'axios'
import { sm2 } from "sm-crypto"

const ipk = "ipk"
export function getIpk() {
  return JSON.parse(sessionStorage.getItem(ipk))
}
export function sign(rd){
  const e = JSON.parse(sessionStorage.getItem(ipk))
  const data = JSON.parse(JSON.stringify(rd))
  return sm2.doSignature(JSON.stringify(data), e.privateKey, { hash: true, der: true })
}

export async function initIpk() {
  const ext = 1000 * 60 * 30
  const res = await axios.get('/xsy-service-web/pk/random')
  const exptime = new Date().getTime() + ext
  res.data.data.exptime = exptime
  sessionStorage.setItem(ipk, JSON.stringify(res.data.data))
  // console.log(store.state.app.ipkInfo)
  setTimeout(() => {
    initIpk()
  }, ext - 1000)
}
